package com.ibangnuo.manage.service.terminal;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibangnuo.framework.domain.*;
import com.ibangnuo.framework.model.response.*;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.CommercialMapper;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import com.ibangnuo.manage.dao.employee.EmployeeRepository;
import com.ibangnuo.manage.dao.shop.MerchantsMapper;
import com.ibangnuo.manage.dao.shop.MerchantsRepository;
import com.ibangnuo.manage.dao.terminal.TerminalMapper;
import com.ibangnuo.manage.dao.terminal.TerminalRepository;
import com.ibangnuo.manage.service.shop.MerchantsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author:ly
 * @Data:2020/1/2 12:02
 * @Verdion:1.0
 */
@Service
public class TerminalService {
    private static Logger LOGGER = LoggerFactory.getLogger(MerchantsService.class);
    @Autowired
    private TerminalRepository terminalRepository;
    @Autowired
    private TerminalMapper terminalMapper;
    @Autowired
    private CommercialMapper commercialMapper;

    @Autowired
    private MerchantsMapper merchantsMapper;
    @Autowired
    private MerchantsRepository merchantsRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private AgentRepository agentRepository;
    @Autowired
    private EmployeeRepository employeeRepository;

    /**
     * 器具查询
     * 1.根据商户id查询所有器具
     * 管理员查询器具
     * 商户查询器具
     * 代理商查询器具
     * 1.先查询出该代理商下的所有商户
     * 员工查询器具
     * 1.查询出员工下的所有代理商
     *
     * @param map
     * @return
     */
    public QueryResponseResult query(Map map) {
        LOGGER.info("器具查询的参数", map);
        if (map == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        Integer page = (Integer) map.get("page");
        Integer size = (Integer) map.get("limit");
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 20;
        }

        QueryResult queryResult = new QueryResult();
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user1.getId();
        if (user1.getType() == 0) {
            map.put("cId", "");//管理员
        } else if (user1.getType() == 2) {
            CommercialTenant commercialTenant = commercialMapper.findByUserId(userId);
            String loginCId = commercialTenant.getId();//商户
            map.put("cId", loginCId);
        } else if (user1.getType() == 1) {
            Agent byUserId = agentRepository.findByUserId(userId);//代理商
            if (byUserId != null) {
                List list = new ArrayList();
                List<CommercialTenant> byAgentId = commercialRepository.findByAgentId(byUserId.getId());
                for (CommercialTenant commercialTenant : byAgentId) {
                    list.add(commercialTenant);
                }
                map.put("commercialId", list);
            } else {
                queryResult.setList(null);
                queryResult.setTotal(0);
                return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
            }
        } else {
            Employee byUserId = employeeRepository.findByUserId(userId);//员工
            List<CommercialTenant> byEmployeeId = commercialRepository.findByEmployeeId(byUserId.getId());
            List<CommercialTenant> list = new ArrayList();
            if (byEmployeeId != null && byEmployeeId.size() > 0) {
                for (CommercialTenant commercialTenant : byEmployeeId) {
                    list.add(commercialTenant);
                }
                map.put("commercialId", list);
            } else {
                queryResult.setList(null);
                queryResult.setTotal(0);
                return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
            }
        }
        PageHelper.startPage(page, size);
        List<Map> all = terminalMapper.findByCId(map);
        for (Map map1 : all) {
            String id = String.valueOf(map1.get("id"));
            Optional<Merchants> byId = merchantsRepository.findById(id);
            if (byId.isPresent()) {
                Merchants merchants = byId.get();
                String name = merchants.getName();
                map1.put("terminalAgentId", name);
            }
        }
        PageInfo<Map> pageInfo = new PageInfo<Map>(all);
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 新版机具查询
     * @param map
     * @return
     */
    public QueryResponseResult findListNew(Map map){
        int page = (int)map.get("page");
        int limit = (int)map.get("limit");
        map.get("limit");
        PageHelper.startPage(page,limit);
        List<Map> terminalList = terminalMapper.findByListNew(map);
        PageInfo pageInfo = new PageInfo(terminalList);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    public QueryResponseResult findListNew2(Map map){
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user1.getId());
        if("1".equals(agent.getHierarchy())){
            //查询全部
            return this.findListNew(map);
        }else{
            //查询旗下的内容
            //查询下面的代理商
            List<String> agentIdList = new ArrayList<>();//包含自己的和下面的
            agentIdList.add(agent.getId());
            List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
            for (Agent agent1 : agentList) {
                agentIdList.add(agent1.getId());
                List<Agent> agent2List = agentRepository.findByParentIdAndIsDelete(agent1.getId(), 1);
                for (Agent agent2 : agent2List) {
                    agentIdList.add(agent2.getId());
                }
            }
            int page = (int)map.get("page");
            int limit = (int)map.get("limit");
            map.get("limit");
            PageHelper.startPage(page,limit);
            //查询商家id
            List<String> commercialIdList = commercialMapper.findIdByAgentId(agentIdList);
            //根据商家id查询机具
            map.put("commercialIdList",commercialIdList);
            List<Map> listNew1 = terminalMapper.findByListNew1(map);
            PageInfo pageInfo = new PageInfo(listNew1);
            QueryResult queryResult = new QueryResult();
            queryResult.setList(pageInfo.getList());
            queryResult.setTotal(pageInfo.getTotal());
            return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
        }


    }


    /**
     * 门店名称查询
     * 1.根据商户id查询所有器具
     *
     * @return
     */
    public QueryResponseResult findName() {
        LOGGER.info("门店名字查询");
        QueryResult queryResult = new QueryResult();
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        List all = new ArrayList();
        if (user1.getType() == 0 || user1.getType() == 1) {
            //管理员查询
            all = merchantsRepository.findAll();

        } else {
            //商户
            String userId = user1.getId();
            CommercialTenant commercialTenant = commercialMapper.findByUserId(userId);
            String loginCId = commercialTenant.getId();
            all = merchantsMapper.findName(loginCId);
        }

        PageInfo<Map> pageInfo = new PageInfo<Map>(all);
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }


    /**
     * 器具添加
     *
     * @return
     */
    public QueryResponseResult addTerminal(Map map) {
        LOGGER.info("器具添加的参数", map);
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        //String loginCId = user1.getCommercialTenantId();
        String userId = user1.getId();
        String shopId = (String) map.get("terminalAgentId");
        Terminal terminal = new Terminal();
        if (user1.getType() == 0) {
            //管理员添加器具
            List<Terminal> terminal1 = terminalRepository.findByShopId(shopId);
            String commercialTenantId = terminal1.get(0).getCommercialTenantId();
            terminal.setCommercialTenantId(commercialTenantId);
        } else {
            //商家添加器具
            CommercialTenant commercialTenant = commercialMapper.findByUserId(userId);
            String loginCId = commercialTenant.getId();
            terminal.setCommercialTenantId(loginCId);
        }
        List<Terminal> list = terminalMapper.findByName(shopId);

        if (list != null && list.size() > 0) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        terminal.setCreateTime(new Date());

        String id = UUID.randomUUID().toString().replace("-", "");
        terminal.setId(id);
        long num = PrimaryKeyUtil.nextId();
        String number = Long.toString(num);
        System.out.println(number);
        terminal.setNum(number);
        terminal.setSate(1);
        terminal.setName(map.get("terminalName").toString());
        terminal.setIsDelete(1);
        terminal.setShopId(shopId);
        String terminalSN = (String) map.get("terminalSN");
        terminal.setSn(terminalSN);
        terminalRepository.save(terminal);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 器具的删除
     *
     * @param id
     * @return
     */
    public QueryResponseResult delTerminal(String id) {

        Terminal terminal = terminalRepository.findById(id).get();
        terminal.setIsDelete(0);
        System.out.println(id);
        terminalRepository.save(terminal);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 器具信息的回显
     *
     * @param id
     * @return
     */
    public QueryResponseResult findById(String id) {

        if (id == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        QueryResult queryResult = new QueryResult();
        List<Map> all = terminalMapper.findById(id);
        //List<Map> all = employeeMapper.queryById(id);
        if (all.size() > 0 && all != null) {
            queryResult.setList(all);
            queryResult.setTotal(all.size());
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        }
        return new QueryResponseResult(CommonCode.FAIL, null);
    }

    /**
     * 器具信息的编辑
     *
     * @param map
     * @return
     */
    public QueryResponseResult upTerminal(Map map) {
        if (map == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        String terminalUuid = (String) map.get("terminalUuid");
        Optional<Terminal> byId = terminalRepository.findById(terminalUuid);
        Terminal terminal = byId.get();
        String terminalAgentId = (String) map.get("terminalAgentId");
        terminal.setShopName(terminalAgentId);
        String terminalSN = (String) map.get("terminalSN");
        terminal.setSn(terminalSN);
        String name = map.get("terminalName").toString();
        terminal.setName(name);
        String terminalNumber = (String) map.get("terminalNumber");
        terminal.setNum(terminalNumber);
        terminal.setSate(Integer.parseInt(String.valueOf(map.get("sate"))));
        terminalRepository.save(terminal);
        return new QueryResponseResult(CommonCode.SUCCESS, null);
    }

    /**
     * 根据sn号查询商户是否授权
     * 1.查询出商家id
     * 2.根据商家id查询商家表获取数据返回
     *
     * @param sn
     * @return
     */
    public ObjectResult findPidBySnNum(String sn) {
        Terminal terminal = terminalRepository.findBySn(sn);
        if (terminal == null) {
            return new ObjectResult(CommonCode.FAIL, null);
        }
        Optional<CommercialTenant> optional = commercialRepository.findById(terminal.getCommercialTenantId());
        if (optional.isPresent()) {
            String pId = optional.get().getPId();
            if (StringUtils.isNotEmpty(pId)) {
                return new ObjectResult(CommonCode.SUCCESS, optional.get());
            }
        }
        return new ObjectResult(CommonCode.FAIL, null);
    }

    /**
     * 门店查询
     * 1.查询出门店id
     * 2.根据门店id查询出门店
     * @param sn
     * @return
     */
    public ObjectResult findShopBySnNum(String sn){
        Terminal terminal = terminalRepository.findBySn(sn);
        Optional<Merchants> optional = merchantsRepository.findById(terminal.getShopId());
        if(optional.isPresent()){
            return new ObjectResult(CommonCode.SUCCESS,optional.get());
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }

    /**
     * 器具添加新版
     * @param terminal
     * @return
     */
    public ResponseResult addNew(Terminal terminal){
        terminal.setCreateTime(new Date());
        terminal.setIsDelete(1);
        terminal.setNum(PrimaryKeyUtil.nextId()+"");
        terminal.setSate(0);
        terminal.setCommercialTenantId(terminal.getCommercialTenantId());
        Optional<Merchants> optional = merchantsRepository.findById(terminal.getShopId());
        terminal.setShopName(optional.get().getName());
        terminalRepository.save(terminal);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
